// src/components/SourceBox.tsx
import React, { useEffect, useRef } from 'react'
import { dragBus } from '../utils/dragBus'
import type { BodyItem } from '../types'

interface SourceBoxProps {
  children: React.ReactNode
  data?: BodyItem
}

// data用于传递组件信息，方便拖拽时获取
const SourceBox: React.FC<SourceBoxProps> = ({ children, data }) => {
  const dragRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (dragRef.current) {
      dragRef.current.draggable = true

      const handleDragStart = (e: DragEvent) => {
        console.log('>>> SourceBox handleDragStart', data)
        if (data) {
          dragBus.setDrag(dragRef.current!, data)
          e.dataTransfer?.setData('text/plain', JSON.stringify(data))
        }
      }

      const handleClick = () => {
        console.log('>>> SourceBox handleClick', data)
        if (data) {
          dragBus.setDrag(dragRef.current!, data)
        }
      }

      dragRef.current.addEventListener('dragstart', handleDragStart)
      dragRef.current.addEventListener('click', handleClick)

      return () => {
        if (dragRef.current) {
          dragRef.current.removeEventListener('dragstart', handleDragStart)
          dragRef.current.removeEventListener('click', handleClick)
        }
      }
    }
  }, [data])

  return (
    <div ref={dragRef} style={{ width: '100%' }}>
      {children}
    </div>
  )
}

export default SourceBox
